﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Slippor.Douban.Radio.Assist;
using Slippor.Utility.WebWorker;
using System.Text.RegularExpressions;
using System.Net;

namespace LyricTrackerPlugin
{
    public class BaiduLrcer:ILrcer
    {
        private const String _urlSongInfor = "http://box.zhangmen.baidu.com/x?op=12&count=1&title={0}$${1}$$$$";//获取歌曲信息的地址
        private const String _urlGeCi = "http://box.zhangmen.baidu.com/bdlrc/";//下载歌词的不完全地址

        private Song _currentSong;
        public String DownloadLrc(Song song)
        {
            if (_currentSong != song)
            {
                _currentSong = song;
            }
            var result = DownloadLrc(song.Album.ArtistString, song.Title);
            if (result == null)
            {
                String songTitle = song.Title;
                if (songTitle.IndexOf('(') > 0)
                {
                    songTitle = songTitle.Substring(0, songTitle.IndexOf('('));
                }
                if (song.Album.Artists.Count > 1)
                {
                    foreach (var artist in song.Album.Artists)
                    {
                        result = DownloadLrc(artist, songTitle);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取歌词
        /// <param name="songName">歌曲名称</param>
        /// <param name="singerName">演唱人</param>
        /// </summary>
        public String DownloadLrc(String singer, String title)
        {
            String tag = String.Format("{0} - {1}", singer, title);
            XmlDocument xml = SearchLrc(singer, title);

            if (xml == null)
            {
                return null;
            }

            var content = xml.InnerXml;
            const string matchLrcid = @"<lrcid>(?<id>\d+)</lrcid>";
            int lrcid = 0;//歌词加密文件名
            var regex = new Regex(matchLrcid);
            MatchCollection matchResult = regex.Matches(content);
            if (matchResult.Count > 0)
            {
                lrcid = Convert.ToInt32(matchResult[0].Groups["id"].Value);
                int fileID = lrcid / 100;//计算出加密后的歌词文件名
                var url = _urlGeCi + fileID + "/" + lrcid + ".lrc";
                var result = GetWebContent(url);
                return result;
            }
            else
            {
                return null;
            }
        }

        public XmlDocument SearchLrc(String singer, String title)
        {
            singer = singer.ToLower().Replace(" ", "").Replace("'", "");
            title = title.ToLower().Replace(" ", "").Replace("'", "");
            var x = GetWebContent(String.Format(_urlSongInfor, title, singer));
            var xml = new XmlDocument();
            try
            {
                xml.LoadXml(x);
            }
            catch
            {
            }
            return xml;
        }

        private readonly IWebWorker _webWorker = new BaiduWebWorker();
        /// <summary>
        /// 获取远程网页内容
        /// </summary>
        /// <param name="url">url地址</param>
        /// <returns></returns>
        private String GetWebContent(string url)
        {
            try
            {
                String result = _webWorker.AchieveResponse(url,null,null,true,RequestMethod.Get);
                return result;
            }
            catch (WebException ex)
            {
                return null;
            }
        }
    }

    public class BaiduWebWorker : Slippor.Utility.WebWorker.AbstractWebWorker
    {
        public BaiduWebWorker()
        {
            _encoding = Encoding.GetEncoding("gb2312");
        }

        protected override byte[] SetLoginInfo(string username, string password)
        {
            throw new NotImplementedException();
        }
    }
}
